<template>
  <div>
    <!-- 筛选条件 -->
    <ContentWrap class="mb-4">
      <el-form :model="filterParams" :inline="true" label-width="80px">
        <el-form-item label="统计维度">
          <el-select v-model="filterParams.dimension" @change="handleDimensionChange" class="!w-200px">
            <el-option label="按计划统计" value="plan" />
            <el-option label="按职业统计" value="profession" />
            <el-option label="按等级统计" value="level" />
            <el-option label="按时间统计" value="time" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="loadStatisticsData"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="评价计划" v-if="filterParams.dimension === 'plan'">
          <el-select v-model="filterParams.planId" @change="loadStatisticsData" class="!w-200px">
            <el-option label="全部计划" :value="null" />
            <el-option
              v-for="plan in planList"
              :key="plan.id"
              :label="plan.planName"
              :value="plan.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadStatisticsData">
            <Icon icon="ep:refresh" class="mr-1" />
            刷新数据
          </el-button>
          <el-button @click="handleExportReport">
            <Icon icon="ep:download" class="mr-1" />
            导出报表
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 总体统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card>
          <div class="flex items-center">
            <div class="flex-1">
              <div class="text-2xl font-bold text-blue-600">{{ overallStats.totalPlans || 0 }}</div>
              <div class="text-gray-500">评价计划总数</div>
            </div>
            <Icon icon="ep:calendar" class="text-4xl text-blue-600" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="flex items-center">
            <div class="flex-1">
              <div class="text-2xl font-bold text-green-600">{{ overallStats.totalCandidates || 0 }}</div>
              <div class="text-gray-500">参评人员总数</div>
            </div>
            <Icon icon="ep:user" class="text-4xl text-green-600" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="flex items-center">
            <div class="flex-1">
              <div class="text-2xl font-bold text-orange-600">{{ overallStats.passedCandidates || 0 }}</div>
              <div class="text-gray-500">通过人数</div>
            </div>
            <Icon icon="ep:check" class="text-4xl text-orange-600" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="flex items-center">
            <div class="flex-1">
              <div class="text-2xl font-bold text-purple-600">{{ overallStats.passRate || 0 }}%</div>
              <div class="text-gray-500">通过率</div>
            </div>
            <Icon icon="ep:pie-chart" class="text-4xl text-purple-600" />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表展示区域 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="12">
        <ContentWrap>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">评价计划统计</h3>
            <el-radio-group v-model="chartType1" @change="updateChart1">
              <el-radio-button label="bar">柱状图</el-radio-button>
              <el-radio-button label="pie">饼图</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="chart1Ref" style="height: 350px;"></div>
        </ContentWrap>
      </el-col>
      <el-col :span="12">
        <ContentWrap>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">通过率趋势</h3>
            <el-radio-group v-model="chartType2" @change="updateChart2">
              <el-radio-button label="line">折线图</el-radio-button>
              <el-radio-button label="area">面积图</el-radio-button>
            </el-radio-group>
          </div>
          <div ref="chart2Ref" style="height: 350px;"></div>
        </ContentWrap>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <ContentWrap>
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">详细统计数据</h3>
        <div>
          <el-button @click="handleRefreshTable">
            <Icon icon="ep:refresh" class="mr-1" />
            刷新
          </el-button>
          <el-button @click="handleExportTable">
            <Icon icon="ep:download" class="mr-1" />
            导出
          </el-button>
        </div>
      </div>
      
      <el-table v-loading="tableLoading" :data="tableData" :stripe="true" :show-overflow-tooltip="true">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="统计项目" align="center" prop="itemName" width="200" />
        <el-table-column label="计划总数" align="center" prop="totalPlans" width="100" />
        <el-table-column label="参评人数" align="center" prop="totalCandidates" width="100" />
        <el-table-column label="通过人数" align="center" prop="passedCandidates" width="100" />
        <el-table-column label="通过率" align="center" prop="passRate" width="100">
          <template #default="scope">
            <el-tag :type="getPassRateTagType(scope.row.passRate)">
              {{ scope.row.passRate }}%
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="平均分" align="center" prop="averageScore" width="100" />
        <el-table-column label="最高分" align="center" prop="maxScore" width="100" />
        <el-table-column label="最低分" align="center" prop="minScore" width="100" />
        <el-table-column label="统计时间" align="center" prop="statisticsTime" width="180" />
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openDetailAnalysis(scope.row)"
            >
              详细分析
            </el-button>
            <el-button
              link
              type="primary"
              @click="openTrendAnalysis(scope.row)"
            >
              趋势分析
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <Pagination
        :total="tableTotal"
        v-model:page="tablePage.pageNo"
        v-model:limit="tablePage.pageSize"
        @pagination="loadTableData"
      />
    </ContentWrap>

    <!-- 详细分析弹窗 -->
    <DetailAnalysis ref="detailAnalysisRef" />
    
    <!-- 趋势分析弹窗 -->
    <TrendAnalysis ref="trendAnalysisRef" />
  </div>
</template>

<script setup lang="ts">
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import DetailAnalysis from './DetailAnalysis.vue'
import TrendAnalysis from './TrendAnalysis.vue'

/** 统计报表 */
defineOptions({ name: 'EvalStatistics' })

const message = useMessage() // 消息弹窗

// 筛选参数
const filterParams = reactive({
  dimension: 'plan',
  dateRange: [],
  planId: null
})

// 总体统计数据
const overallStats = ref({
  totalPlans: 0,
  totalCandidates: 0,
  passedCandidates: 0,
  passRate: 0
})

// 图表相关
const chart1Ref = ref()
const chart2Ref = ref()
const chartType1 = ref('bar')
const chartType2 = ref('line')

// 表格相关
const tableLoading = ref(false)
const tableData = ref([])
const tableTotal = ref(0)
const tablePage = reactive({
  pageNo: 1,
  pageSize: 10
})

// 计划列表
const planList = ref<EvalPlanVO[]>([])

/** 加载统计数据 */
const loadStatisticsData = async () => {
  try {
    // 加载总体统计
    await loadOverallStats()
    
    // 更新图表
    updateChart1()
    updateChart2()
    
    // 加载表格数据
    await loadTableData()
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

/** 加载总体统计 */
const loadOverallStats = async () => {
  // 模拟数据，实际应该调用API
  overallStats.value = {
    totalPlans: 25,
    totalCandidates: 1250,
    passedCandidates: 1050,
    passRate: 84
  }
}

/** 加载表格数据 */
const loadTableData = async () => {
  tableLoading.value = true
  try {
    // 模拟数据，实际应该调用API
    tableData.value = [
      {
        itemName: '电工技能等级认定',
        totalPlans: 5,
        totalCandidates: 250,
        passedCandidates: 210,
        passRate: 84,
        averageScore: 82.5,
        maxScore: 95,
        minScore: 65,
        statisticsTime: '2024-12-19 10:00:00'
      },
      {
        itemName: '焊工技能等级认定',
        totalPlans: 3,
        totalCandidates: 180,
        passedCandidates: 150,
        passRate: 83.3,
        averageScore: 81.2,
        maxScore: 92,
        minScore: 62,
        statisticsTime: '2024-12-19 10:00:00'
      }
    ]
    tableTotal.value = 10
  } finally {
    tableLoading.value = false
  }
}

/** 维度变更处理 */
const handleDimensionChange = () => {
  loadStatisticsData()
}

/** 更新图表1 */
const updateChart1 = () => {
  // 实现图表更新逻辑
  console.log('更新图表1:', chartType1.value)
}

/** 更新图表2 */
const updateChart2 = () => {
  // 实现图表更新逻辑
  console.log('更新图表2:', chartType2.value)
}

/** 刷新表格 */
const handleRefreshTable = () => {
  loadTableData()
}

/** 导出表格 */
const handleExportTable = () => {
  message.success('导出功能开发中...')
}

/** 导出报表 */
const handleExportReport = () => {
  message.success('导出报表功能开发中...')
}

/** 详细分析 */
const detailAnalysisRef = ref()
const openDetailAnalysis = (row: any) => {
  detailAnalysisRef.value.open(row)
}

/** 趋势分析 */
const trendAnalysisRef = ref()
const openTrendAnalysis = (row: any) => {
  trendAnalysisRef.value.open(row)
}

/** 获取通过率标签类型 */
const getPassRateTagType = (rate: number) => {
  if (rate >= 90) return 'success'
  if (rate >= 80) return 'primary'
  if (rate >= 70) return 'warning'
  return 'danger'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取所有状态的计划
    const allPlans = await Promise.all([
      getPlanListByStatus(3), // 已发布
      getPlanListByStatus(4), // 进行中
      getPlanListByStatus(5)  // 已完成
    ])
    planList.value = allPlans.flat()
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 */
onMounted(() => {
  loadPlanList()
  loadStatisticsData()
})
</script>

<style scoped>
.text-2xl {
  font-size: 1.5rem;
  line-height: 2rem;
}

.font-bold {
  font-weight: 700;
}

.text-blue-600 {
  color: #2563eb;
}

.text-green-600 {
  color: #16a34a;
}

.text-orange-600 {
  color: #ea580c;
}

.text-purple-600 {
  color: #9333ea;
}

.text-gray-500 {
  color: #6b7280;
}

.text-lg {
  font-size: 1.125rem;
  line-height: 1.75rem;
}

.font-semibold {
  font-weight: 600;
}
</style>
